package com.glorysoft.xztpda.ui.trackin

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.customview.customView
import com.afollestad.materialdialogs.customview.getCustomView
import com.afollestad.materialdialogs.lifecycle.lifecycleOwner
import com.glorysoft.xztpda.entity.ui.ToastMessageBean
import com.glorysoft.xztpda.BR
import com.glorysoft.xztpda.R
import com.glorysoft.xztpda.base.BaseActivity
import com.glorysoft.xztpda.bindingadapter.CarrierCheckAdapter
import com.glorysoft.xztpda.databinding.ActivityTrackInMaterialCarrierBinding
import com.glorysoft.xztpda.entity.LotInfoEntity
import com.huawei.hms.hmsscankit.ScanUtil
import com.huawei.hms.ml.scan.HmsScan
import kotlinx.android.synthetic.main.activity_track_in_guide.*
import kotlinx.android.synthetic.main.activity_track_in_material_carrier.*

/**
 * FileName: TrackInCarrierMaterialActivity
 * Author: XJH
 * Date: 2022/4/12 17:24
 * Description:
 * History:
 */
class TrackInCarrierMaterialActivity : BaseActivity<TrackInBaseViewModel,ActivityTrackInMaterialCarrierBinding>(),
        View.OnClickListener {

    private var mCarrierAdapter : CarrierCheckAdapter? = null

    override fun layoutId(): Int {
        return R.layout.activity_track_in_material_carrier
    }

    override fun initVariableId(): Int {
        return BR.trackInBaseViewModel
    }

    override fun initView(savedInstanceState: Bundle?) {
//        setTitle("开始作业")
        viewModel.lotInfoEntity = intent.getSerializableExtra("LOTINFO") as LotInfoEntity
        val itemEqpList = intent.getSerializableExtra("ITEMEQP") as List<String>?
        if (itemEqpList != null){
            viewModel.mAddCarrierAdapter.setNewData(itemEqpList)
        }
        val type = intent.getStringExtra("TYPE")
        setTitle("开始作业" + "-" +viewModel.lotInfoEntity?.lot?.stepdesc)
        addActivity(this)
        setRightListener("提交"){
            val checkList = mCarrierAdapter!!.checkList
            for (i in 0 until checkList.size()) {
                if (!checkList[i]) {
                    viewModel.defUI.toastEvent.value = ToastMessageBean("当前有载具未校验",false)
                    return@setRightListener
                }
            }

            if (viewModel.materialItems.isNotEmpty()) {
                viewModel.materialItems.forEach{
                    if (it.mlotid.isEmpty()){
                        viewModel.defUI.toastEvent.value = ToastMessageBean("当前有物料批号未填入",false)
                        return@setRightListener
                    }
                }
            }

            viewModel.checkMaterialList(type)
        }

        viewModel.initMaterialList()
    }

    override fun initData() {
//        viewModel.getMaterialInfo()
        ivCarrierScan.setOnClickListener(this)
        mCarrierAdapter = CarrierCheckAdapter(viewModel.lotInfoEntity?.durablelist)
        rvCarrierList.adapter = mCarrierAdapter
        scanCarrier()

        viewModel.defUI.startActivity.observe(this){
            finishAllActivity()
        }

        viewModel.defUI.callObserve.observe(this){
            if (it.type == 201){
                getCustomDialog(it.item as String).show()
            }else{
                startScanForCode(this,1000 + viewModel.scanPos)
            }
        }
    }

    /**
     * 载具验证
     */
    private fun scanCarrier() {
        initEdit(etCarrier,object : EditTextListener{
            override fun onTextChangeListener(s: String) {
                etCarrier.setText("")
                Handler().postDelayed({ etCarrier.requestFocus() }, 500)
                checkCarrier(s)
            }

        })
    }


    private fun checkCarrier(s : String) {
        if (mCarrierAdapter?.data == null || mCarrierAdapter?.data!!.size <= 0) {
            return
        }

        val data = mCarrierAdapter?.data
        for (i in data?.indices!!) {
            if (data[i].equals(s, ignoreCase = true)) {
                if (mCarrierAdapter?.checkList?.get(i)!!) {
                    viewModel.defUI.toastEvent.value = ToastMessageBean("当前载具已校验",false)
                } else {
                    mCarrierAdapter?.setCheck(s)
                }
                return
            }
        }
        viewModel.defUI.toastEvent.value = ToastMessageBean("当前载具不匹配",false)
    }


    override fun onClick(v: View?) {
        when(v?.id){
            R.id.ivCarrierScan -> startScanForCode(this,10001)
        }
    }

    private fun getCustomDialog(code : String): MaterialDialog {
        val dialog = MaterialDialog(this)
                .cancelable(false)
                .cornerRadius(12f)
                .customView(R.layout.check_material, noVerticalPadding = true)
                .lifecycleOwner(this)
        val contentView = dialog.getCustomView()
        val ivClose: ImageView = contentView.findViewById(R.id.ivClose)
        val tv3: TextView = contentView.findViewById(R.id.tv3)
        ivClose.setOnClickListener {
            dialog.dismiss()
        }

        tv3.setOnClickListener {
            viewModel.setMaterial(code)
            dialog.dismiss()
        }

        return dialog
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {

        // 当扫码页面结束后，处理扫码结果。
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != RESULT_OK || data == null) {
            viewModel.scanPos = -1
            return
        }
        if (resultCode == RESULT_OK){
            // 从onActivityResult返回data中，用ScanUtil.RESULT作为key值取到HmsScan返回值。
            when (val obj: Any = data.getParcelableExtra(ScanUtil.RESULT)) {
                is HmsScan -> {
                    val barCode = obj.getOriginalValue()
                    when(requestCode){
                        10001 -> {
                            checkCarrier(barCode)
                        }
                        1000 + viewModel.scanPos ->{
//                            if (viewModel.scanPos >= 0){
//                                viewModel.materialItems[viewModel.scanPos].mlotid = barCode
//                            }
                            viewModel.checkMaterial(barCode)
                        }
                    }

                }
            }


        }

    }

}